package com.bw.lib_image

import android.app.ActivityManager
import android.content.Context
import android.os.StatFs

/**
 * 内存管理
 * 1.区分低端设备和高端设备
 * 2.内存不足情况时的处理
 */
object GlideCacheManager {
    //默认缓存位置
    private const val DEFAULT_MEN_CACHE_SIZE = 1024 * 1024 * 24 //内存缓存默认24M
    private const val DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 250//磁盘缓存250M
    private const val LOW_MEMORY_DEVICE_MULTIPLIER = 0.5f //低端设备0.5倍
    private const val HIGH_MEMORY_DEVICE_MULTIPLIER = 5F    //高端设备5倍

    /**
     * 计算内存大小
     */
    fun calculateMemoryCacheSize(context: Context): Long {
        val baseSize = when{
            isHighMemoryDevice(context) -> DEFAULT_MEN_CACHE_SIZE * HIGH_MEMORY_DEVICE_MULTIPLIER // 高端设备
            else -> DEFAULT_MEN_CACHE_SIZE * LOW_MEMORY_DEVICE_MULTIPLIER
        }.toLong()
        //内存不足
        return if (isLowMemoryDevice(context)) baseSize/2 else baseSize
    }

    /**
     * 计算磁盘大小
     */
    fun calculateDiskCacheSize(context: Context): Long {
        val cacheDir = context.cacheDir //data/data/包名/cache
        val stat = StatFs(cacheDir.path)    //获得目录的状态
        val available = stat.availableBlocksLong //可用空间
        val blockSizeLong = stat.blockSizeLong  //每块大小
        val baseSize = available * blockSizeLong    //可用总大小

        //可用空间的15%,不超过1G
        return minOf((baseSize * 0.15).toLong(), 1024 * 1024 * 1024L)
    }


    /**
     * 判断当前设备是低端还是高端
     */
    private fun isHighMemoryDevice(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        //大于3G的高内存设备
        return memoryInfo.totalMem > 3L * 1024 * 1024 * 1024
    }

    /**
     * 内存不足
     */
    private fun isLowMemoryDevice(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        //大于3G的高内存设备
        return memoryInfo.lowMemory
    }

    /**
     * 清理内存缓存
     */
    fun clearMemoryCache(context: Context) {
        GlideApp.get(context).clearMemory()
    }

    /**
     * 清理磁盘缓存
     */
    fun clearDiskCache(context: Context) {
        GlideApp.get(context).clearDiskCache()
    }
}